package cn.catsdad.service.impl;

import cn.catsdad.base.service.impl.BaseServiceImpl;
import cn.catsdad.dto.NotifierDTO;
import cn.catsdad.dto.UserDTO;
import cn.catsdad.repository.NotifierRepository;
import cn.catsdad.service.api.NotifierService;
import cn.catsdad.service.api.UserService;
import cn.catsdad.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 通知人service实现
 *
 * @author xuyonglong
 * @version V1.0 2023/5/11
 */
@Service
public class NotifierServiceImpl extends BaseServiceImpl<NotifierDTO, Long, NotifierRepository> implements NotifierService {

    private UserService userService;

    @Override
    @Transactional
    public void deleteByNoticeIds(Collection<Long> noticeIds) {
        if (StringUtil.isNotEmpty(noticeIds)) {
            repository.deleteByNoticeIdIn(noticeIds);
        }
    }

    @Override
    public Map<Long, List<NotifierDTO>> queryByNoticeIds(Collection<Long> noticeIds) {
        Map<Long, List<NotifierDTO>> result = new HashMap<>(noticeIds.size());
        if (StringUtil.isNotEmpty(noticeIds)) {
            List<NotifierDTO> notifiers = repository.findByNoticeIdIn(noticeIds);
            fillingTransientFields(notifiers);
            result = notifiers.stream().collect(Collectors.groupingBy(NotifierDTO::getNoticeId));
        }
        return result;
    }

    /**
     * 填充临时数据
     *
     * @param notifiers 通知人集合
     */
    private void fillingTransientFields(List<NotifierDTO> notifiers) {
        if (StringUtil.isNotEmpty(notifiers)) {
            Set<Long> userIds = notifiers.stream().map(NotifierDTO::getUserId).collect(Collectors.toSet());
            Map<Long, UserDTO> userMap = userService.queryMap(userIds);
            for (NotifierDTO notifier : notifiers) {
                UserDTO user = userMap.get(notifier.getUserId());
                notifier.setUserName(user == null ? "" : user.getUserName());
            }
        }
    }

    @Autowired
    @Lazy
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
